package com.java.servlet;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author jingjintao
 * @date 2021/6/16 - 0:18
 **/
public class HelloServlet implements Servlet {

    public HelloServlet() {
        System.out.println("1. servlet构造器方法");
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        System.out.println("2. servlet init 方法");

        System.out.println("HelloServlet程序的别名是:"+servletConfig.getServletName());
        System.out.println("初始化参数username的值是:"+servletConfig.getInitParameter("username"));
        System.out.println("初始化参数url的值是:"+servletConfig.getInitParameter("url"));
        //获取servletContext对象
        System.out.println(servletConfig.getServletContext());

    }

    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
        System.out.println("3.servlet service方法 ==== HelloServlet 被访问了");

        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        //获取请求方式
        String method = httpServletRequest.getMethod();
        if("GET".equals(method)){
            doGet();
        }else if("POST".equals(method)){
            doPost();
        }
    }

    /**
     * 处理get请求
     */
    public void doGet(){
        System.out.println("get 请求");
    }

    /**
     * 处理post请求
     */
    public void doPost(){
        System.out.println("post请求");
    }

    @Override
    public String getServletInfo() {
        return null;
    }

    @Override
    public void destroy() {
        System.out.println("4. servlet destroy方法");
    }
}
